import axios from "axios";
import { getToken, getUserInfo, removeToken, setToken, setUserInfo } from "../utils/auth";
import router from "../router";
import { error, success, warning } from "../utils/message";
import store from "../store/index";
// import data from "./data.json";
// 添加请求拦截器
axios.interceptors.request.use(function(config) {
    // 在发送请求之前做些什么
    config.headers['Content-Type'] = 'application/json; charset=utf-8';
    // 请求头带上token
    config.headers['token'] = getToken();
    return config;
}, function(error) {
    // 对请求错误做些什么
    console.log(error);
    return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(function(response) {
    // 对响应数据做点什么
    return response;
}, function(error) {
    if (error.toString().indexOf("status code 401") > 1) {
        warning("系统超时，请登录后再操出");
        removeToken();
        store.commit("logoutMutation", {});
        router.push({ path: "/login", query: { redirect: router.currentRoute.value.fullPath } });
    } else {
        // 对响应错误做点什么
        return Promise.reject(error);
    }

});

function getUserId() {
    let userInfo = getUserInfo();
    return userInfo ?.idUsersinfo;
}

/**
 * 获取系统验证码
 * @returns {Promise<AxiosResponse<any>>}
 */
export function getValidateImg() {
    return getRequest("/system-config/global/imageCode");
}

/**
 * 菜单选择树
 * @param data
 * @returns {[]}
 */
export function selectMenusTreeData(data) {
    let list = [];
    data.forEach(item => {
        let temp = {};
        temp["value"] = item.idMenusinfo;
        temp["label"] = item.menuName;
        if (item.children && item.children.length > 0) {
            temp["children"] = [];
            item.children.forEach(sitem => {
                let stemp = {};
                stemp["value"] = sitem.idMenusinfo;
                stemp["label"] = sitem.menuName;
                temp["children"].push(stemp);
            });
        }
        list.push(temp);
    });
    return list;
}

/**
 * 用户登录
 * @param data
 * @returns {Promise<AxiosResponse<any>>}
 */
export function userLogin(data, redirect, recall) {
    postRequest("/system-config/system/usersAuditEntity/userLogin", data).then(res => {
        let redata = res.data;
        let userData = redata.data;
        if (redata.code === 1) {
            warning(redata.cnMessage);
            if (recall) {
                recall(-1);
            }
        } else {
            try {
                let condition = {
                    "userId": userData.idUsersinfo,
                };
                store.commit("loginMutation", userData);
                setToken(userData.dataNo, data.rememberMe);
                // userData.rolesList = [];
                setUserInfo(userData);
                permissionMenus(condition, -1).then(res2 => {
                    // console.log(res2);
                    let redata2 = createRouterAndMenuList(res2.data.data);
                    store.commit("permissionMenusMutation", redata2);
                    router.push({ path: redirect || "/" });
                });
            } catch (e) {
                console.log(e);
                removeToken();
                router.push({ path: redirect || "/" });
            }

        }

    }).catch(error => {
        console.log("登录异常")
        warning(error);
    });
}

/**
 * 退出登录
 * @param data
 * @returns {Promise<AxiosResponse<any>>}
 */
export function userLogout(data) {
    postRequest("/system-config/system/usersAuditEntity/userLogout", data).then(res => {
        let redata = res.data;
        if (redata.code === 1) {
            warning(redata.cnMessage);
        } else {
            removeToken()
            store.commit("logoutMutation", data);
            router.push({
                path: "/login",
                query: { redirect: router.currentRoute.fullPath, query: router.currentRoute.query }
            });
        }
    }).catch(err => error(err));
}

/**
 * 一次性加载用户权限菜单
 * @param data
 * @returns {Promise<AxiosResponse<any>>}
 */
export function permissionMenus(data, sysId) {
    let userId = data.userId || getUserId();
    return postRequest(`/system-config/system/menusinfoEntity/permissionMenus/${userId}/${sysId}`, {});

}

export function permissionResources(data) {
    let userId = data.userId || getUserId();
    return postRequest(`/system-config/system/resourcesEntity/permissionResources/${userId}/${data.menuId}`, {})
}

/**
 * 创建路由和菜单数据
 * @param redata
 * @returns {[]}
 */
export function createRouterAndMenuList(redata) {
    let leftMenuDatas = [];
    if (!redata) {
        //  redata = data;
        return;
    }
    let index=1;
    redata.forEach(item => {
        if(item.menuPath=="#"&&item.children?.length==0){
            return;
        }
        let path = item.menuPath.startsWith("/") ? item.menuPath : "/" + item.menuPath;
        let data = {
            path: path,
            component: () =>
                import ("@/components" + path),
            name: item.menuCode,
            menuIcon: item.menuIcon,
            children: [],
            meta: {
                title: item.menuName,
                menuId: item.idMenusinfo||"0-"+(index++),
                keepAlive: item.keepAlive || false
            }
        };
        router.addRoute("Index", data);
        if (item.children && item.children.length > 0) {
            item.children.forEach(sitem => {
                let spath = sitem.menuPath.startsWith("/") ? sitem.menuPath : "/" + sitem.menuPath;
                let sdata = {
                    path: spath,
                    component: () =>
                        import ("@/components" + spath),
                    name: sitem.menuCode,
                    menuIcon: sitem.menuIcon,
                    children: [],
                    meta: {
                        title: sitem.menuName,
                        menuId: sitem.idMenusinfo||"0-"+(index++),
                        keepAlive: sitem.keepAlive || false
                    }
                };
                router.addRoute("Index", sdata);
                if (sitem.children && sitem.children.length > 0) {
                    sitem.children.forEach(ssitem => {
                        let sspath = ssitem.menuPath.startsWith("/") ? ssitem.menuPath : "/" + ssitem.menuPath;
                        let ssdata = {
                            path: sspath,
                            component: () =>
                                import ("@/components" + sspath),
                            name: ssitem.menuCode,
                            menuIcon: ssitem.menuIcon,
                            children: [],
                            meta: {
                                title: ssitem.menuName,
                                menuId: ssitem.idMenusinfo||"0-"+(index++),
                                keepAlive: ssitem.keepAlive || false
                            }
                        };
                        router.addRoute("Index", ssdata);
                        sdata.children.push(ssdata);
                    });
                }

                data.children.push(sdata);
            });
        }
        leftMenuDatas.push(data);
        //初始化时已经拿到所有权限菜单到路由
    });
    return leftMenuDatas;
}

/**
 * 下载文件,
 * @param url 路径
 * @param param 参数
 */
export function download(url, param) {
    return new Promise((resolve, reject) => {
        axios.post(url, param, { responseType: "blob" }).then(res => {
            let blob = new Blob([res.data]);
            let delement = document.createElement("a");
            let href = window.URL.createObjectURL(blob);
            delement.href = href;
            let name = decodeURI(res.headers["content-disposition"].split("=")[1]);
            delement.download = name;
            document.body.appendChild(delement);
            delement.click();
            document.body.removeChild(delement);
            window.URL.revokeObjectURL(href);
            resolve();
        }).catch(err => {
            reject(err);
        });
    });
}

/**
 * 加载已配置的菜单
 * @param param
 * @returns {Promise<AxiosResponse<*>>}
 */
export function loadConfigedMenus(param) {
    return postRequest("/system-config/system/menusinfoEntity/getAllByCondition", param);

}

/**
 * 获取部门信息
 * @param param
 * @returns {Promise<AxiosResponse<*>>}
 */
export function loadDepartments(param) {
    return new Promise((resolve, reject) => {
        postRequest("/system-config/system/departmentEntity/getAllByCondition", param).then(res => {
            if (res.data.code != 0) {
                reject(res.data.cnMessage);
            } else {
                let resdata = res.data.data;
                resolve(resdata)
            }

        }).catch(err => reject(err))
    })

}

/**
 * 获取部门信息
 * @param param
 * @returns {Promise<AxiosResponse<*>>}
 */
export function loadSystems(param) {
    return new Promise((resolve, reject) => {
        postRequest("/system-config/system/informationsEntity/getAllByCondition", param).then(res => {
            if (res.data.code != 0) {
                reject(res.data.cnMessage);
            } else {
                let resdata = res.data.data;
                resolve(resdata)
            }

        }).catch(err => reject(err))
    })

}

/**
 * 获取下拉数据
 * @param param
 * @returns {Promise<unknown>}
 */
export function loadSelectDatas(param) {
    return new Promise((resolve, reject) => {
        postRequest("/system-config/system/statusinfoEntity/getAllByCondition", param).then(res => {
            if (res.data.code != 0) {
                reject(res.data.cnMessage);
            } else {
                let resdata = res.data.data;
                resolve(resdata)
            }

        }).catch(err => reject(err))
    })
}

/**
 * 获取下拉数据
 * @param param
 * @returns {Promise<unknown>}
 */
export function loadRoleDatas(param) {
    return new Promise((resolve, reject) => {
        postRequest("/system-config/system/rolesinfoEntity/queryUserAllRoles", param).then(res => {
            if (res.data.code != 0) {
                reject(res.data.cnMessage);
            } else {
                let resdata = res.data.data;
                resolve(resdata)
            }

        }).catch(err => reject(err))
    })
}

/**
 * Post 请求
 * @param url
 * @param data
 * @returns {Promise<AxiosResponse<any>>}
 */
export function postRequest(url, data) {
    return axios.post(url, data);
}

/**
 * Get请求
 * @param url
 * @returns {Promise<AxiosResponse<any>>}
 */
export function getRequest(url) {
    return axios.get(url);

}
/**
 * Post Upload 请求
 * @param url
 * @param data
 * @returns {Promise<AxiosResponse<any>>}
 */
export function uploadRequest(url, data) {
    return axios.post(url, data, { "Content-Type": "multipart/form-data" });
}
/**
 * 去除空格
 * @param data
 * @returns {*}
 */
export function trim(data) {
    if (!data) {
        return data;
    }
    return data.replace(/(^\s*)|(\s*$)/g, '');
}

//修改密码方法
export function pwdMerge(that) {
    that.$refs.ruleForm.validate((valid) => {
        if (!valid) {
            return;
        }
        let pwd = that.ruleForm.password;
        let rePwd = that.ruleForm.rePassword;
        if (!trim(pwd)) {
            warning("不能设置空格密码");
            return;
        }
        if (pwd.length < 6 || pwd.length > 15) {
            warning("请设置长度为6到15的密码");
            return;
        }
        if (pwd !== rePwd) {
            warning("两次密码不一致，请重新录入");
            return;
        }
        postRequest("/system-config/system/usersAuditEntity/refreshInvalidPassword/" + that.ruleForm.username +
            "/" + pwd + "/" + (that.ruleForm.oldPassword || "0") + "/" + that.ruleForm.phone, {}).then(res => {
            let redata = res.data;
            if (redata.code == 1) {
                warning(redata.cnMessage);
                return;
            }
            success(redata.cnMessage);
            that.dialogPwdVisible = !that.dialogPwdVisible;
        });
    });
}